﻿using System;
using System.IO;
using System.Reflection;

namespace YSCommander
{
	/// <summary>
	/// Gets the data folders.
	/// </summary>
	public static class DataFolder
	{
		/// <summary>
		/// Gets the path to the apllication data folder.
		/// </summary>
		/// <returns>The path to the apllication data folder.</returns>
		public static string GetApplicationDataFolder()
		{
			// Getting copyright
			var assembly = Assembly.GetEntryAssembly();

			assembly = assembly ?? Assembly.GetExecutingAssembly();

			if (assembly == null)
			{
				throw new ApplicationException("Can't get assembly.");
			}

			var attributes = assembly.GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);

			string companyName = (attributes.Length != 0) ? ((AssemblyCompanyAttribute)attributes[0]).Company : null;

			// Getting assembly name
			var assemblyName = assembly.GetName().Name;

			var path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

			if (string.IsNullOrEmpty(companyName))
			{
				path = Path.Combine(path, assemblyName);
			}
			else
			{
				path = Path.Combine(path, companyName);
				path = Path.Combine(path, assemblyName);
			}

			return path;
		}

		/// <summary>
		/// Creates the application data folder, if the folder does not exist.
		/// </summary>
		/// <returns>The application data folder.</returns>
		public static string CreateApplicationDataFolder()
		{
			var path = GetApplicationDataFolder();

			if (!Directory.Exists(path))
			{
				Directory.CreateDirectory(path);
			}

			return path;
		}

		/// <summary>
		/// Gets the full path to a data file.
		/// </summary>
		/// <remarks>
		/// The method automatically creates folder, if the folder does not exist.
		/// </remarks>
		/// <param name="fileName">The file name (with extention).</param>
		/// <returns>The full path to a data file.</returns>
		/// <exception cref="ArgumentOutOfRangeException">
		/// If fileName is null or empty.
		/// </exception>
		public static string GetApplicationDataFileName(string fileName)
		{
			if (string.IsNullOrEmpty(fileName))
			{
				throw new ArgumentOutOfRangeException("fileName");
			}

			var path = CreateApplicationDataFolder();

			path = Path.Combine(path, fileName);

			return path;
		}
	}
}
